package com.cmict.data.form.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.cmict.data.form.api.entity.dataobject.SysFormDO;
import com.cmict.data.form.api.service.SysFormService;
import com.cmict.data.form.api.task.dto.SysFromSeachDataVoDTO;
import com.cmict.data.form.api.util.UUIDUtils;
import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.form.api.entity.SysTableColumn;
import com.cmict.data.form.api.entity.vo.*;
import com.cmict.data.form.api.service.SysCurrencyService;
import com.cmict.data.form.api.util.Base64Utils;
import com.cmict.data.form.api.util.FileUtil;
import com.cmict.data.framework.security.core.util.SecurityFrameworkUtils;
import com.cmict.data.system.api.sql.SqlParameterCheck;
import com.cmict.data.system.api.encodedetails.dict.dto.EncodeBodyDTD;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.cmict.data.form.api.constant.FormConstants.PARAMETER_MSG;
import static com.cmict.data.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cmict.data.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.cmict.data.system.enums.ErrorCodeConstants.*;


/**
 * @author : qiaoyu
 * @description :
 * @create : 2021-8-5
 **/

@Api(tags = "后台管理-表单引擎")
@RestController
@RequestMapping("/form/project")
@RequiredArgsConstructor
public class SysCurrencyController {
    private static final Logger logger = LoggerFactory.getLogger(SysCurrencyController.class);

    private final SysCurrencyService sysCurrencyService;
    private final SysFormService sysFormService;

    @Value("${platform.fileupload.upload-folder}")
    private String uploadFolder;

    @Value("${spring.datasource.dynamic.datasource.slave.name}")
    private String teble;

    @Value("${platform.number.size}")
    private int platformFileSize;

    @Value("${platform.isAdaptationOldData}")
    private int isAdaptationOldData;

    @ApiOperation(value = "适配老数据方法")
    @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public CommonResult isAdaptationOldData() {
        logger.info("isAdaptationOldData : "+isAdaptationOldData);
        if(1 == isAdaptationOldData){
            return CommonResult.success(sysCurrencyService.isAdaptationOldData());
        }
        return CommonResult.success("isAdaptationOldData : "+isAdaptationOldData);
    }

    @ApiOperation(value = "创建数据库表整合")
    @PostMapping(value = "/createFormTableAll")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult createFormTableAll(@RequestBody SysFormTableAllVo sysFormTableAllVo) throws Exception {
        return sysCurrencyService.createFormTableAll(sysFormTableAllVo);
    }

    @ApiOperation(value = "修改数据库表整合")
    @PostMapping(value = "/editFormTableAll")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult editFormTableAll(@RequestBody SysFormTableAllVo sysFormTableAllVo) throws Exception {
        return sysCurrencyService.editFormTableAll(sysFormTableAllVo);
    }

    @ApiOperation(value = "增加数据库表字段整合")
    @PostMapping(value = "/addColumnTableAll")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addColumnTableAll(@RequestBody SysFormTableAllVo sysFormTableAllVo) throws Exception {
        return sysCurrencyService.addColumnTableAll(sysFormTableAllVo);
    }

    @ApiOperation(value = "获取业务库所有表名")
    @GetMapping(value = "/getTableNameList")
    public CommonResult<List<String>> getTableNameList() throws Exception {
        String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
        return CommonResult.success(sysCurrencyService.getTableNameList(sql));
    }

    @ApiOperation(value = "获取业务库表名过滤表单")
    @GetMapping(value = "/getTableNameListForm")
    public CommonResult<List<String>> getTableNameListForm() throws Exception {
        String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
        return CommonResult.success(sysCurrencyService.getTableNameListForm(sql));
    }

    @ApiOperation(value = "创建数据库表")
    @PostMapping(value = "/createtable")
    public CommonResult createtable(@RequestBody SysFromTableVo sysFromVo) throws Exception {
        return sysCurrencyService.createTable(sysFromVo);
    }

    @ApiOperation(value = "创建数据库表")
    @PostMapping(value = "/updatatablecolumn")
    public CommonResult updatatablecolumn(@RequestBody SysFromTableVo sysFromVo) throws Exception {
        return sysCurrencyService.updatatablecolumn(sysFromVo);
    }

    @ApiOperation(value = "批量创建数据库表")
    @PostMapping(value = "/createtablelist")
    public CommonResult createtablelist(@RequestBody List<SysFromTableVo> sysFromVoList) throws Exception {
        for (SysFromTableVo vo:sysFromVoList){
            sysCurrencyService.createTable(vo);
        }
        return CommonResult.success("创建成功",true);
    }

    @ApiOperation(value = "增加数据库表字段")
    @PostMapping(value = "/addccolumntable")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addccolumntable(@RequestBody SysFromTableVo sysFromVo) throws Exception {
        return sysCurrencyService.addcColumnTable(sysFromVo);
    }

    @ApiOperation(value = "删除数据库表字段")
    @PostMapping(value = "/deleteColumntable")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult deleteColumntable(@RequestBody List<SysFromTableDeleteColumnVo> sysFromTableDeleteColumnVoList) throws Exception {
        if(sysFromTableDeleteColumnVoList.size()>0){
            for (int i = 0; i <sysFromTableDeleteColumnVoList.size() ; i++) {
                SysFromTableDeleteColumnVo sysFromTableDeleteColumnVo = sysFromTableDeleteColumnVoList.get(i);
                if(ObjectUtil.isEmpty(sysFromTableDeleteColumnVo.getTableName())){
                    return CommonResult.error(500,"请传入表名");
                }
                if(sysFromTableDeleteColumnVo.getFieldNameList().size()==0){
                    return CommonResult.error(500,"请选择传入字段");
                }
                List<String> columnList = sysCurrencyService.getColumnName(sysFromTableDeleteColumnVo.getTableName());
                for (int j = 0; j <sysFromTableDeleteColumnVo.getFieldNameList().size() ; j++) {
                    if(columnList.contains(sysFromTableDeleteColumnVo.getFieldNameList().get(j))){
                        sysCurrencyService.deleteColumnTable(sysFromTableDeleteColumnVo.getTableName(),sysFromTableDeleteColumnVo.getFieldNameList().get(j));
                    }
                }
            }
            return CommonResult.success( "删除成功",true);
        }
        return CommonResult.error(500,"无修改内容");
    }


    @ApiOperation(value = "表单数据插入（主、子）事务")
    @PostMapping(value = "/insertdataall")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult insertdataall(@RequestBody SysInsertVo sysInsertVo) throws Exception {
       /*if(!valueRegexp(sysInsertVo)){
            return CommonResult.error(400,"参数类型不正确");
        }*/
        String creator = null;
        if(StringUtils.isNotEmpty(sysInsertVo.getSysFromInsertDataVo().getDataType())) {
            SqlParameterCheck.checkMatch(sysInsertVo.getSysFromInsertDataVo().getDataType());
        }
        try {
            List<SysFromDataColumnVo> sysFromDataColumnList = sysInsertVo.getSysFromInsertDataVo().getData().stream().filter(item->item.getName().equals("data_id")).collect(Collectors.toList());
            SysFromDataColumnVo dataId = new SysFromDataColumnVo();
            String data_id = UUIDUtils.dateRandom18();
            if(sysFromDataColumnList.size() == 0){
                //生成data_id
                dataId.setValue(data_id);
                dataId.setName("data_id");
                dataId.setType("bigint");
                sysInsertVo.getSysFromInsertDataVo().getData().add(dataId);
                SysFromDataColumnVo creatorform = new SysFromDataColumnVo();
                Long userId = SecurityFrameworkUtils.getLoginUser().getId();
                creatorform.setValue(String.valueOf(userId));
                creatorform.setName("creator");
                creatorform.setType("bigint");
                sysInsertVo.getSysFromInsertDataVo().getData().add(creatorform);
            }else{
                String dataid = null;
                List<SysFromDataColumnVo> sysFromDataColumnListdataId = sysInsertVo.getSysFromInsertDataVo().getData();
                for (SysFromDataColumnVo vo : sysFromDataColumnListdataId) {
                    if("data_id".equals(vo.getName())){
                        dataid = vo.getValue();
                    }
                }
                String sql = "SELECT DISTINCT creator FROM " + teble + "." + sysInsertVo.getSysFromInsertDataVo().getTableName() + " WHERE data_id = '" + dataid + "'";
                creator =  sysCurrencyService.getCreator(sql);
                SysFromDataColumnVo creatorform = new SysFromDataColumnVo();
                creatorform.setValue(String.valueOf(creator));
                creatorform.setName("creator");
                creatorform.setType("bigint");
                sysInsertVo.getSysFromInsertDataVo().getData().add(creatorform);
            }
            CommonResult returndata = sysCurrencyService.insertData(sysInsertVo.getSysFromInsertDataVo());
           /* if(returndata.getMsg().equals(PARAMETER_MSG)){
                return CommonResult.success(PARAMETER_MSG,returndata.getData());
            }*/
            //String id = String.valueOf(returndata.getData());
            if(ObjectUtil.isNotEmpty(data_id)){
                SysFromDataColumnVo vodate = new SysFromDataColumnVo();
                List<SysFromDataColumnVo> data = sysInsertVo.getSysFromInsertDataVo().getData();
                for (SysFromDataColumnVo vo :data) {
                    if(vo.getName().equals("data_id")){
                        vodate.setValue(vo.getValue());
                    }
                }
                vodate.setName("parent_id");
                vodate.setType("bigint");
                for (SysFromInsertDataVo vo : sysInsertVo.getSysFromInsertDataVoList()){
                    vo.getData().add(vodate);
                    List<SysFromDataColumnVo> sysFromDataColumnSonList = vo.getData().stream().filter(item->item.getName().equals("data_id")).collect(Collectors.toList());
                    if(sysFromDataColumnSonList.size() == 0){
                        SysFromDataColumnVo subDataId = new SysFromDataColumnVo();
                        subDataId.setValue(UUIDUtils.dateRandom18());
                        subDataId.setName("data_id");
                        subDataId.setType("bigint");
                        vo.getData().add(subDataId);
                        SysFromDataColumnVo subcreator = new SysFromDataColumnVo();
                        Long userId = SecurityFrameworkUtils.getLoginUser().getId();
                        subcreator.setValue(String.valueOf(userId));
                        subcreator.setName("creator");
                        subcreator.setType("bigint");
                        vo.getData().add(subcreator);
                    }else{
                        SysFromDataColumnVo subcreator = new SysFromDataColumnVo();
                        subcreator.setValue(creator);
                        subcreator.setName("creator");
                        subcreator.setType("bigint");
                        vo.getData().add(subcreator);
                    }
                    vo.setRepeatVerifyList(sysInsertVo.getSysFromInsertDataVo().getRepeatVerifyList());
                    CommonResult returndatachild = sysCurrencyService.insertDataChild(vo);
                    if(returndatachild.getMsg().equals(PARAMETER_MSG)){
                        return CommonResult.success(PARAMETER_MSG,returndatachild.getData());
                    }
                }
            }
            return returndata;
        } catch (Exception e) {
            throw exception(TABLE_DATA_DELETE_ERROR);
        }
    }

   /* @ApiOperation(value = "自定义表插入数据")
    @PostMapping(value = "/insertdata")
    public CommonResult insertdata(@RequestBody SysFromInsertDataVo sysFromInsertDataVo) throws Exception {
        try {
            return sysCurrencyService.insertData(sysFromInsertDataVo);
        } catch (Exception e) {
            return CommonResult.error(500,"插入数据失败，数据库字段不匹配");
        }
    }

	@ApiOperation(value = "多表插入数据")
	@PostMapping(value = "/insertdatalist")
	public CommonResult insertdatalist(@RequestBody List<SysFromInsertDataVo> sysFromInsertDataVoList) throws Exception {
        try {
            for (SysFromInsertDataVo vo : sysFromInsertDataVoList){
               sysCurrencyService.insertDataChild(vo);
            }
            return CommonResult.success("全部数据插入成功",true);
        } catch (Exception e) {
            return CommonResult.error(500,"插入数据失败，数据库字段不匹配");
        }
	}*/

    @ApiOperation(value = "表单数据修改（主、子）事务")
    @PostMapping(value = "/updataall")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updataall(@Validated @RequestBody SysUpdataVo sysUpdataVo) throws Exception {
        /*if(!valueRegexp(sysUpdataVo)){
            return CommonResult.error(400,"参数类型不正确");
        }*/
        try {
            CommonResult returndata = sysCurrencyService.upData(sysUpdataVo.getSysFromUpDataVo());;
            if(returndata.getMsg().equals(PARAMETER_MSG)){
                return CommonResult.success(PARAMETER_MSG,returndata.getData());
            }
            CommonResult returndatachild = sysCurrencyService.upDataList(sysUpdataVo.getSysFromUpDataListVo(),sysUpdataVo.getSysFromUpDataVo().getDataId(),sysUpdataVo.getSysFromUpDataVo().getRepeatVerifyList());
            if(returndatachild.getMsg().equals(PARAMETER_MSG)){
                return CommonResult.success(PARAMETER_MSG,returndatachild.getData());
            }
            return CommonResult.success("数据操作成功",true);
        } catch (Exception e) {
            throw exception(TABLE_DATA_DELETE_ERROR);
        }
    }

    @ApiOperation(value = "自定义表修改数据")
    @PostMapping(value = "/updata")
    public CommonResult updata(@RequestBody SysFromUpDataVo sysFromUpDataVo) throws Exception {
        return sysCurrencyService.upData(sysFromUpDataVo);
    }

    @ApiOperation(value = "自定义表修改数据")
    @PostMapping(value = "/updatedatalist")
    public CommonResult updatedatalist (@RequestBody List<SysFromUpDataVo> sysFromUpDataListVo) throws Exception {
        return sysCurrencyService.upDataList(sysFromUpDataListVo,null,null);
    }

    @ApiOperation(value = "自定义表删除数据")
    @DeleteMapping(value = "/deletedata")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult deletedata(String tableName, String ids){
        String regex = "^$|[0-9\\,\\x22]+$";
        if(!ids .matches(regex)) {
            return CommonResult.error(500, "参数不符合规则");
        }
        try {
            SysFormDO sysForm = sysFormService.selectOneByTableName(tableName);
            List<String> idList = Arrays.asList(ids.split(","));
            for (int i = 0; i <idList.size() ; i++) {
                String sqlget = "SELECT data_id FROM " + teble + "." + tableName  + " where id = " + idList.get(i) + "";
                String dataId= String.valueOf(sysCurrencyService.getDataId(sqlget));
                String sql = "DELETE FROM " + teble + "." + tableName + " where data_id = " + dataId + "";
                sysCurrencyService.deleteData(sql);
                List<SysFormDO> sysFormList = sysFormService.getChildSysFormByIds(sysForm.getId());
                if (ObjectUtil.isNotEmpty(sysFormList)) {
                    for (int j = 0; j < sysFormList.size(); j++) {
                        String sqlkids = "DELETE FROM " + teble + "." + sysFormList.get(j).getTableName() + " where parent_id = " + dataId + "";
                        sysCurrencyService.deleteData(sqlkids);
                    }
                }
            }
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            throw exception(TABLE_DATA_DELETE_ERROR);
        }
    }

    @ApiOperation(value = "清空数据表")
    @DeleteMapping(value = "/deletedataAll")
    public CommonResult deletedataAll(String tableName) throws Exception {
        String sql = "TRUNCATE TABLE  "+ tableName ;
        sysCurrencyService.deleteDataAll(sql);
        return CommonResult.success("删除成功");
    }

    @GetMapping("/data-page")
    @ApiOperation(value = "根据表单id获取表单数据", notes = "在【表单发布】界面中，进行调用")
    public CommonResult getProcessInstanceStatus(@Valid SysFromSeachDataVoDTO sysFromSeachData) {
        return sysCurrencyService.getFormDataAndStatus(getLoginUserId(),sysFromSeachData);
    }

    @ApiOperation(value = "获取库表列表（排除当前表单与子表单）")
    @GetMapping(value = "/getTableListExcludeForm")
    public CommonResult getTableListExcludeForm(@RequestParam(required = false)Long formId,@RequestParam(required = false)String tableName) throws Exception {
        if(ObjectUtil.isEmpty(formId)){
            String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
            List<String> tableNameLIst = sysCurrencyService.getTableNameList(sql);
            return  CommonResult.success("获取成功",tableNameLIst);
        }
        return sysCurrencyService.getTableListExcludeForm(formId,tableName);
    }

    @ApiOperation(value = "自定义查找数据列表")
    @PostMapping(value = "/getListData")
    public CommonResult getListData(@RequestBody SysFromSeachDataVo sysFromSeachData) {
        try {
            String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
            List<String> tableNameLIst = sysCurrencyService.getTableNameList(sql);
            if(tableNameLIst.contains(sysFromSeachData.getTableName())){
                return sysCurrencyService.selectData(sysFromSeachData);
            }
        } catch (Exception e) {
            return CommonResult.error(500,"获取数据失败，数据库不存在");
        }
        return CommonResult.error(500,"获取数据失败，数据库不存在");
    }

    @ApiOperation(value = "查找子表单数据列表")
    @PostMapping(value = "/getChildListData")
    public CommonResult getChildListData(@RequestBody SysFormChildDataVo sysFormChildDataVo) throws Exception {
        String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
        List<String> tableNameLIst = sysCurrencyService.getTableNameList(sql);
        List<SysReturnChildDataVo> sysReturnChildDataList = new ArrayList<>();
        for (int i = 0; i <sysFormChildDataVo.getTableNames().size() ; i++) {
            if(tableNameLIst.contains(sysFormChildDataVo.getTableNames().get(i))){
                /*String sqlget = "SELECT data_id FROM " + teble + "." + sysFormChildDataVo.getTableNames().get(i) + " where data_id = " + sysFormChildDataVo.getId() + "";
                String dataId= sysCurrencyService.getDataId(sqlget);*/
                List<Map<String,Object>> data = sysCurrencyService.selectChildData(sysFormChildDataVo.getTableNames().get(i), sysFormChildDataVo.getId(), sysFormChildDataVo.getVersionId());
                SysReturnChildDataVo sysReturnChildDataVo = new SysReturnChildDataVo();
                sysReturnChildDataVo.setData(data);
                sysReturnChildDataVo.setTableName(sysFormChildDataVo.getTableNames().get(i));
                sysReturnChildDataList.add(sysReturnChildDataVo);
            }else{
                return CommonResult.success("数据库表名不存在！");
            }
        }
        return CommonResult.success("获取成功",sysReturnChildDataList);
    }

    @ApiOperation(value = "查找全部数据列表")
    @GetMapping(value = "/getAllListData")
    public CommonResult getAllListData(String tableName) throws Exception {
        try {
            String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
            List<String> tableNameLIst = sysCurrencyService.getTableNameList(sql);
            if(tableNameLIst.contains(tableName)){
                return sysCurrencyService.selectAllData(tableName,"form");
            }
            return CommonResult.success("数据库表名不存在！");
        } catch (Exception e) {
            return CommonResult.error(500,"获取数据失败，数据库不存在");
        }
    }
    @ApiOperation(value = "查找全部数据列表")
    @GetMapping(value = "/getAllListDataForm")
    public CommonResult getAllListDataForm(String tableName) throws Exception {
        try {
            String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
            List<String> tableNameLIst = sysCurrencyService.getTableNameList(sql);
            if(tableNameLIst.contains(tableName)){
                return sysCurrencyService.selectAllDataForm(tableName,"form");
            }
            return CommonResult.success("数据库表名不存在！");
        } catch (Exception e) {
            return CommonResult.error(500,"获取数据失败，数据库不存在");
        }
    }
    @ApiOperation(value = "查找批量指定数据集合")
    @GetMapping(value = "/getIdsData")
    public CommonResult getIdsData(String tableName,String ids) throws Exception {
        try {
            String sql = "select table_name from information_schema.tables where table_schema='"+teble+"';";
            List<String> tableNameLIst = sysCurrencyService.getTableNameList(sql);
            if(tableNameLIst.contains(tableName)){
                return sysCurrencyService.selectIdsData(tableName,ids);
            }
            return CommonResult.success("数据库表名不存在！");
        } catch (Exception e) {
            return CommonResult.error(500,"获取数据失败，数据库不存在");
        }
    }

    @ApiOperation(value = "表单规则ALL")
    @PostMapping(value = "/formFieldRules")
    public CommonResult formFieldRulesAll(@RequestBody List<SysFormFieldRulesVo> sysFormFieldRulesVoList) throws Exception {
        SysFieldRuleReturnVo vo = new SysFieldRuleReturnVo();
        Boolean isok = true;
        String count = "";
        for (int i = 0; i <sysFormFieldRulesVoList.size() ; i++) {
            SysFieldRuleReturnVo sysFieldRuleReturnVo = (SysFieldRuleReturnVo) sysCurrencyService.formFieldRules(sysFormFieldRulesVoList.get(i)).getData();
            if(ObjectUtil.isNotEmpty(sysFieldRuleReturnVo) && ObjectUtil.isNotEmpty(sysFieldRuleReturnVo.getDispalyField())){
                isok = false;
                List<String> dispalyList = Arrays.asList(sysFieldRuleReturnVo.getDispalyField().split(","));
                for (int j = 0; j <dispalyList.size() ; j++) {
                    if(!count.contains(dispalyList.get(j))){
                        count = count + dispalyList.get(j) + ",";
                    }
                }
            }
        }
        if(isok){
            return CommonResult.success("无通过规则",null);
        }
        vo.setDispalyField(count);
        return CommonResult.success("通过规则",vo);
    }

    @ApiOperation(value = "获取单条数据，通过id")
    @GetMapping(value = "/getDataOneId")
    public CommonResult getDataOneId(String tableName,Integer id) throws Exception {
        String sql = "SELECT * FROM " + tableName + " where id = "+ id +"";
        Map<Object,Object> data = sysCurrencyService.getDataOne(sql);
        return CommonResult.success("获取成功", data );
    }

    @ApiOperation(value = "excel导入")
    @PostMapping(value = "/excelinput")
    public CommonResult excelInput(@RequestParam(value = "file") MultipartFile file) {
        try{
            return sysCurrencyService.createFromExcel(file);
        }catch (Exception e) {
            return CommonResult.error(500, "上传文件表头格式不符合要求");
        }
    }

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/fileUpload")
    public Map<String,String> fileUpload(@RequestParam(value = "file") MultipartFile file) {
        return FileUtil.fileUpload(file,uploadFolder);
    }

    @ApiOperation(value = "文件上传消息附件")
    @PostMapping(value = "/fileUploadMessages")
    public CommonResult fileUploadMessages(@RequestParam(value = "file") MultipartFile file) {
        SysFileUpload sysFileUpload = new SysFileUpload();
        Map<String,String> map = FileUtil.fileUpload(file,uploadFolder);
        for(String key : map.keySet()) {
            if(key.equals("name")){
                String value = map.get(key);
                sysFileUpload.setName(value);
            }
            if(key.equals("url")){
                String value = map.get(key);
                sysFileUpload.setUrl(value);
            }
        }
        return CommonResult.success(sysFileUpload);
    }

    @ApiOperation(value = "文件上传Base64")
    @PostMapping(value = "/fileUploadBase64")
    public CommonResult fileUploadBase64(@RequestBody SysBase64VO base64) {
        logger.info("----- base64 -------"+base64);
        String imageName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        String urlPath = Base64Utils.base64ToFile(uploadFolder, base64.getBase64(), imageName);
        File file=new File(urlPath);
        if(ObjectUtil.isNotEmpty(file)){
            return CommonResult.success(uploadFolder + imageName);
        }
        return CommonResult.error(500,"上传失败！");
    }

    @ApiOperation(value = "创建库表FLT")
    @PostMapping(value = "/createtableFlt")
    public CommonResult createtableFlt (@RequestBody SysFromTableVo sysFromTable) throws Exception {
        return sysCurrencyService.createTableFlt(sysFromTable);
    }

    @ApiOperation(value = "自定义表导入数据")
    @PostMapping(value = "/excelImportData")
    public CommonResult importData(HttpServletRequest servletRequest)throws Exception{
        try {
            MultiValueMap<String, MultipartFile> fileMap = ((StandardMultipartHttpServletRequest) servletRequest).getMultiFileMap();
            MultipartFile file = fileMap.get("file").get(0);
            //表名（主表传主表，单独上传子表就传子表表名）
            String tableName = servletRequest.getParameter("tableName");
            //单独导入子表单数据需要带上关联主表数据的id
            String parentId = servletRequest.getParameter("parentId");
            //新增/更新
            String updateType = servletRequest.getParameter("updateType");
            int size = (int) file.getSize();
            int max = platformFileSize;
            if(size > max){
                return CommonResult.error(500,"数据文件太大了");
            }
            CommonResult result = sysCurrencyService.importData(file,tableName,updateType,parentId);
            return result;
        } catch (Exception e) {
            return CommonResult.error(500,"excel模板不符合要求，请重新下载");
        }
    }

    @GetMapping("/get-import-template")
    @ApiOperation("根据表名获得导入模板")
    public void importTemplate(String tableName,HttpServletResponse response) {
        try{
            sysCurrencyService.importTemplate(tableName,response);
        }catch (Exception e){
            logger.error("获取模板失败" + e);
        }
    }

    @GetMapping("/getDataOut")
    @ApiOperation("根据表名导出数据")
    public void getDataOut(String tableName, String ids, String sortField, String sortType, HttpServletResponse response) throws Exception{
        try{
            sysCurrencyService.getDataOut(tableName,ids,sortField,sortType,response);
        }catch (IOException e){
            logger.error("获取模板失败" + e);
        }
    }


    @ApiOperation(value = "修改表结构")
    @PostMapping(value = "/alter-table-st")
    public CommonResult alterTableSt(@RequestBody SysFromTableStructureVo sysFromTableStructure) throws Exception {
        return sysCurrencyService.alterTableSt(sysFromTableStructure);
    }


    @ApiOperation(value = "获取数据库中所有表名")
    @GetMapping(value = "/getTableName")
    public CommonResult getTableName(){
        return CommonResult.success("获取成功",sysCurrencyService.getTableName());
    }


    @ApiOperation(value = "获取表中所有字段")
    @GetMapping(value = "/getColumn")
    public CommonResult getColumn(String tableName){
        List<SysTableColumn> list = sysCurrencyService.getColumn(tableName);
        list.forEach(sysTableColumn ->{
            sysTableColumn.setColumn(sysTableColumn.getColumnName()+"_"+sysTableColumn.getColumnComment());
        });
        return CommonResult.success("获取成功",list);
    }

    @ApiOperation(value = "根据formid获取所有字段")
    @GetMapping(value = "/getColumnOfFormId")
    public CommonResult getColumnOfFormId(Long formId){
        SysFormDO form = sysFormService.getSysForm(formId);
        if(ObjectUtil.isNotEmpty(form) && ObjectUtil.isNotEmpty(form.getTableName())){
            List<SysTableColumn> list = sysCurrencyService.getColumn(form.getTableName());
            list.forEach(sysTableColumn ->{
                sysTableColumn.setColumn(sysTableColumn.getColumnName()+"_"+sysTableColumn.getColumnComment());
            });
            return CommonResult.success("获取成功",list);
        }else{
            return CommonResult.error(500,"表单已不存在");
        }
    }

    @ApiOperation(value = "获取表中设计字段")
    @GetMapping(value = "/getFieldColumn")
    public CommonResult getFieldColumn(String tableName){
        List<SysTableColumn> list = sysCurrencyService.getColumn(tableName);
        List<SysTableColumn> reList = new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            if(!list.get(i).getColumnName().equals("id") && !list.get(i).getColumnName().equals("creator") && !list.get(i).getColumnName().equals("data_type")
                    && !list.get(i).getColumnName().equals("create_time")
                    && !list.get(i).getColumnName().equals("update_time")
                    && !list.get(i).getColumnName().equals("tenant_id")
                    && !list.get(i).getColumnName().equals("parent_id"))
            {
                reList.add(list.get(i))	;
            }
        }
        reList.forEach(sysTableColumn ->{
            sysTableColumn.setColumn(sysTableColumn.getColumnName()+"_"+sysTableColumn.getColumnComment());
        });
        return CommonResult.success("获取成功",reList);
    }

    @ApiOperation(value = "获取表中某字段数据")
    @PostMapping(value = "/getData")
    public CommonResult getData(@Validated @RequestBody SysDatasourceVO sysDatasourceVO){
        return CommonResult.success("获取成功",sysCurrencyService.getData(sysDatasourceVO));
    }

    @ApiOperation(value = "获取表中某字段数据-适配SELECT")
    @PostMapping(value = "/getDataSelect")
    public CommonResult getDataSelect(@Validated @RequestBody SysDatasourceVO sysDatasourceVO){
        return sysCurrencyService.getDataSelect(sysDatasourceVO);
    }

    @ApiOperation(value = "表字段计算")
    @PostMapping(value = "/getColumnFormula")
    public CommonResult getColumnFormula(@RequestBody SysFromColumnFormulaVo sysFromColumnFormulaVo){
        return CommonResult.success("获取成功",sysCurrencyService.getColumnFormula(sysFromColumnFormulaVo));
    }

    @ApiOperation(value = "面板设计统计")
    @PostMapping(value = "/getGatewayColumnFormula")
    public CommonResult getGatewayColumnFormula(@RequestBody SysFromColumnFormulaVo sysFromColumnFormulaVo){
        return CommonResult.success("获取成功",sysCurrencyService.getGatewayColumnFormula(sysFromColumnFormulaVo));
    }

    @ApiOperation(value = "获取自动码")
    @PostMapping(value = "/getAutomaticCode")
    public CommonResult getAutomaticCode(@Validated @RequestBody EncodeBodyDTD encodeBodyDTD){
        return sysCurrencyService.getEncode(encodeBodyDTD.getTableName(),encodeBodyDTD.getColumn(),encodeBodyDTD.getMonitorMap(), encodeBodyDTD.getEncodeId());
    }

    @ApiOperation(value = "数据联动获取表单联动数据")
    @PostMapping(value = "/getLinkData")
    public CommonResult getLinkageData(@RequestBody List<SysLinkAgeDataVo> sysLinkAgeDataVoList){
        List<SysKeyValueVo> list = new ArrayList<>();
        for (int i = 0; i <sysLinkAgeDataVoList.size() ; i++) {
            SysLinkAgeDataVo sysLinkAgeDataVo = sysLinkAgeDataVoList.get(i);
            Map<Object, Object> object = sysCurrencyService.getLinkageData(sysLinkAgeDataVo);
            if(ObjectUtil.isNotEmpty(object)){
                Set<Object> keySet = object.keySet();
                for (Object key : keySet ) {
                    SysKeyValueVo sysKeyValueVo = new SysKeyValueVo();
                    sysKeyValueVo.setKey(sysLinkAgeDataVo.getReturnField());
                    sysKeyValueVo.setValue(object.get(key));
                    list.add(sysKeyValueVo);
                }
            }else{
                return CommonResult.success("无数据");
            }
        }
        return CommonResult.success("获取成功",list);
    }

    @ApiOperation(value = "数据联动获取表字段排除默认字段")
    @GetMapping(value = "/getColumnNameClean")
    public CommonResult getColumnNameClean(String tableName){
        List<SysTableColumn> sysTableColumn = sysCurrencyService.getColumn(tableName);
        List<Map<Object,Object>> columnNames = new ArrayList<>();
        for (int i = 0; i <sysTableColumn.size() ; i++) {
            if(!"id,creator,data_type,create_time,update_time,tenant_id,parent_id".contains(sysTableColumn.get(i).getColumnName())){
                Map<Object,Object> map = new HashMap<>();
                map.put(sysTableColumn.get(i).getColumnName(),sysTableColumn.get(i).getDataType());
                columnNames.add(map);
            }
        }
        return CommonResult.success("获取成功",columnNames);
    }

    @ApiOperation(value = "数据关联获取表单关联数据")
    @PostMapping(value = "/getRelationData")
    public CommonResult getRelationData(@RequestBody SysLinkAgeDataVo sysLinkAgeDataVo){
        return CommonResult.success("获取成功",sysCurrencyService.getRelationData(sysLinkAgeDataVo));
    }

    @ApiOperation(value = "级联组件数据源数据获取")
    @PostMapping(value = "/getCascadeData")
    public CommonResult getCascadeData(@Validated @RequestBody SysCascadeVo sysCascadeVo){
        return CommonResult.success("获取成功",sysCurrencyService.getCascadeData(sysCascadeVo));
    }

    @ApiOperation(value = "表单提交校验")
    @PostMapping(value = "/fromSubmitCheck")
    public CommonResult fromSubmitCheck(@RequestBody SysSubmitCheckVo sysSubmitCheckVo){
        String msg = "";
        Boolean ret = true;
        for (int i = 0; i <sysSubmitCheckVo.getSysFieldFormListVoList().size() ; i++) {
            SysFieldFormListVo sysFieldFormListVo = sysSubmitCheckVo.getSysFieldFormListVoList().get(i);
            Map<Object,Object> object = sysCurrencyService.fromSubmitCheck(sysFieldFormListVo,sysSubmitCheckVo.getTableName());
            if(ObjectUtil.isNotEmpty(object)){
                msg = msg + sysFieldFormListVo.getFiledName()+"数据重复；";
                ret = false;
            }
        }
        if(ret){
            return CommonResult.success("校验通过");
        }
        return CommonResult.error(500,msg);
    }

    @ApiOperation(value = "远端数据关联查询带id返回")
    @PostMapping(value = "/getDistanceData")
    public CommonResult getDistanceData(String tableName,String fieldName, String linkName){
        return CommonResult.success("获取成功",sysCurrencyService.getDistanceData(tableName,fieldName,linkName));
    }

    @ApiOperation(value = "获取字段String求和与去重")
    @GetMapping(value = "/getDataSunRemoval")
    public CommonResult getDataSunRemoval(String tableName,String fieldName,String fun){
        return sysCurrencyService.getDataSunRemoval(tableName,fieldName,fun);
    }
    /**
     * 批量下载文件 支持多个下载
     * 格式 zip包
     *
     * @param vesList
     */
    @GetMapping("/vesDataPoc")
    public void vesDataPoc(HttpServletResponse response, String vesList) {
        List<String> veses = Arrays.asList(vesList.split(";"));
        sysCurrencyService.vesDataPocDownload(veses, response);
    }
    /**
     * 全部下载文件 支持多个下载
     * 格式 zip包
     *
     */
    @GetMapping("/vesDataPocAll")
    public void vesDataPocAll(String tableName, String fieldNameList, HttpServletResponse response) {
        List<String> fieldNames = Arrays.asList(fieldNameList.split(";"));
        sysCurrencyService.vesDataPocDownloadAll(tableName,fieldNames, response);
    }

    /**
     * 判断有无附件
     * 格式 zip包
     *
     */
    @GetMapping("/isNullFile")
    public CommonResult isNullFile(String tableName, String fieldNameList, HttpServletResponse response) {
        List<String> fieldNames = Arrays.asList(fieldNameList.split(";"));
        return sysCurrencyService.isNullFile(tableName,fieldNames,response);
    }

    /**
     * 子表单单独导入数据
     *
     */
    @ApiOperation(value = "excel导入（子表单）")
    @PostMapping(value = "/excelInputChildForm")
    public CommonResult excelInputChildForm(HttpServletRequest servletRequest) throws Exception {
        MultiValueMap<String, MultipartFile> fileMap = ((StandardMultipartHttpServletRequest) servletRequest).getMultiFileMap();
        MultipartFile file = fileMap.get("file").get(0);
        //表名（主表传主表，单独上传子表就传子表表名）
        String tableName = servletRequest.getParameter("tableName");
        return sysCurrencyService.excelInputChildForm(file,tableName);
    }
    /**
     * 获取历史版本
     */
    @ApiOperation(value = "获取历史版本")
    @GetMapping(value = "/getVesion")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult getVesion(String tableName,Long id) throws Exception {
        return sysCurrencyService.getVesion(tableName,id);
    }
    /**
     * js联动获取数据
     */
    @ApiOperation(value = "js联动获取数据")
    @GetMapping(value = "/getJsData")
    public CommonResult getJsData(String tableName,String fieldName,String fieldType,String value) throws Exception {
        return sysCurrencyService.getJsData(tableName,fieldName,fieldType,value);
    }

    public Boolean valueRegexp(SysInsertVo sysInsertVo) throws Exception {
        for (int i = 0; i <sysInsertVo.getSysFromInsertDataVo().getData().size() ; i++) {
            String value = sysInsertVo.getSysFromInsertDataVo().getData().get(i).getValue();
            String reg = "^[\\u4E00-\\u9FA5A-Za-z0-9\\,.!?:;\"，。：；“？！$\\x22_]+$";
            //^((?!123|777).)*$
            Boolean b = value.matches(reg);
            if(!b){
                return b;
            }
        }
        for (int i = 0; i <sysInsertVo.getSysFromInsertDataVoList().size() ; i++) {
            SysFromInsertDataVo vo = sysInsertVo.getSysFromInsertDataVoList().get(i);
            for (int j = 0; j <vo.getData().size(); j++) {
                String value = vo.getData().get(i).getValue();
                String reg = "^[\\u4E00-\\u9FA5A-Za-z0-9\\,.!?:;\"，。：；“？！$\\x22_]+$";
                Boolean b = value.matches(reg);
                if(!b){
                    return b;
                }
            }
        }
        return true;
    }
    public Boolean valueRegexp(SysUpdataVo sysUpdataVo) throws Exception {
        for (int i = 0; i <sysUpdataVo.getSysFromUpDataVo().getData().size() ; i++) {
            String value = sysUpdataVo.getSysFromUpDataVo().getData().get(i).getValue();
            String reg = "^[\\u4E00-\\u9FA5A-Za-z0-9\\,.!?:;\"，。：；“？！$\\x22_]+$";
            Boolean b = value.matches(reg);
            if(!b){
                return b;
            }
        }
        for (int i = 0; i <sysUpdataVo.getSysFromUpDataListVo().size() ; i++) {
            SysFromUpDataVo vo = sysUpdataVo.getSysFromUpDataListVo().get(i);
            for (int j = 0; j <vo.getData().size(); j++) {
                String value = vo.getData().get(i).getValue();
                String reg = "^[\\u4E00-\\u9FA5A-Za-z0-9\\,.!?:;\"，。：；“？！$\\x22_]+$";
                Boolean b = value.matches(reg);
                if(!b){
                    return b;
                }
            }
        }
        return true;
    }

}
